import axios from 'axios'
import {MessageBox, Message } from 'element-ui'

const server = axios.create({
    baseURL:"https://lianghj.top:8888/api/private/v1/", //线上接口
    timeout:5000
})
//请求拦截
server.interceptors.request.use(config => {
    let token=localStorage.getItem('token')
    if(token){
        config.headers.Authorization=token
    }
    return config
}, error => {
    Promise.reject(error)
})
//响应拦截
server.interceptors.response.use(res => {
   let code=res.data.meta.status 
   if(res.data.meta.msg=="无效token"){
     MessageBox.confirm('token过期, 是否跳转到登录页面?', '提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //原生js方法跳转
        location.href='/login'

      }).catch(() => {
      })
   }
//错误状态码
if (code === 400|| code === 401 || code === 403|| code === 404|| code === 500) {
    Message.error({
      duration:1000,
      message: res.data.meta.msg
  })
}

  return res.data

}, error => {
  //接口请求，响应错误-一般都是网络问题，进行处理
     console.log('响应错误',error);
     let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    }
    else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    }
    
    Message({
      message: message,
      type: 'error',
      duration: 1000
    })

    Promise.reject(error)
})
export default server    